import request from '@/utils/request'
import { sha256 } from '@/utils/crypto/sha256'
const CryptoJS = require('crypto-js')
const api = 'File/'

// 上传文件
export function upload({ data, file }) {
  const { filePath, fileName } = data
  const isHidden = true
  const anonymous = false
  var fd = new FormData()
  fd.append('file', file)
  return new Promise((res, rej) => {
    caculate_sha256(file).then(sha256_content => {
      fd.append('fileSha256', sha256_content)
      fd.append('isHidden', isHidden)
      fd.append('filepath', filePath)
      fd.append('filename', fileName)
      fd.append('anonymous', anonymous)
      request.post('file/upload', fd, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(data => {
        res(data)
      }).catch(e => rej(e))
    }).catch(e => rej(e))
  })
}

// Get files by file path
export function getFilesFromPath({ userId, path, fileName }) {
  return request.get(`${api}FromPath`,
    { userId, path, fileName }
  )
}

// load file information by id
function caculate_sha256(contractFile) {
  return new Promise((res, rej) => {
    const reader = new FileReader()
    const blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice
    reader.readAsArrayBuffer(blobSlice.call(contractFile))
    reader.onload = (evt) => {
      const fileBuffer = evt.target.result
      const content = arrayBufferToWordArray(fileBuffer)
      const shaResult = sha256(content)
      res(shaResult)
    }
    reader.onerror = (e) => { rej(e) }
  })
}
function arrayBufferToWordArray(ab) {
  var i8a = new Uint8Array(ab)
  var a = []
  for (var i = 0; i < i8a.length; i += 4) {
    a.push(i8a[i] << 24 | i8a[i + 1] << 16 | i8a[i + 2] << 8 | i8a[i + 3])
  }
  return CryptoJS.lib.WordArray.create(a, i8a.length)
}

export function download(id) {
  request.get(`${api}download`, {
    params: { fileid: id }
  })
}

export function load({ id, userid, filename }) {
  return request.get(`${api}load`, {
    params: { id, userid, filename }
  })
}
